package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.common.Constant;
import com.bnyy.gbp.customsView.ScaleImageView;
import com.bnyy.gbp.permission.PermissionHelper;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.PopupWindowHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.activity.MedicalHousekeeperHomePageActivity;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.ShareData;
import com.bnyy.medicalHousekeeper.fragment.EmptyFragment;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.ContactUser;
import com.bnyy.message.bean.chat.message_data.UserHomePageMessage;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.HashSet;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/12/2
 **/
public class UserHomePageActivity extends BaseActivityImpl {
    @BindView(R.id.iv)
    ScaleImageView iv;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.iv_followed)
    ImageView ivFollowed;
    @BindView(R.id.tv_operate)
    TextView tvOperate;
    @BindView(R.id.iv_chat)
    ImageView ivChat;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.iv_change)
    ImageView ivChange;
    @BindView(R.id.view_pager)
    ViewPager2 viewPager;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.tv_like_count)
    TextView tvLikeCount;
    @BindView(R.id.tv_fans_count)
    TextView tvFansCount;
    @BindView(R.id.tv_focus_count)
    TextView tvFocusCount;
    @BindView(R.id.tv_user_info)
    TextView tvUserInfo;
    @BindView(R.id.ll_operate)
    LinearLayout llOperate;

    private ContactUser mContactUser;
    private int userId;
    private int roleId;

    public static void show(Context context, int userId, int roleId) {
        Intent intent = new Intent(context, UserHomePageActivity.class);
        intent.putExtra("userId", userId);
        intent.putExtra("roleId", roleId);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_home_page;
    }

    @Override
    public String getTitleStr() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        userId = getIntent().getIntExtra("userId", -1);
        roleId = getIntent().getIntExtra("roleId", -1);

        if (userInfoManager.getLoginUserId() == userId) {
            tvUserInfo.setVisibility(View.VISIBLE);
            tvUserInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    show(mContext, UserInfoActivity.class);
                }
            });
        } else {
            llOperate.setVisibility(View.VISIBLE);

            tvOperate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mContactUser.isFollowed()) {
                        ChatMessageActivity.show(mContext, mContactUser);
                    } else {
                        focusOrNot();
                    }
                }
            });
            ivFollowed.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    focusOrNot();
                }
            });
            ivChat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ChatMessageActivity.show(mContext, mContactUser);
                }
            });
        }

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        viewPager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return new EmptyFragment();
            }

            @Override
            public int getItemCount() {
                return 3;
            }
        });

        new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position) {
                    case 0:
                        tab.setText("动态");
                        break;
                    case 1:
                        tab.setText("收藏");
                        break;
                    case 2:
                        tab.setText("赞过");
                        break;
                }
            }
        }).attach();
    }

    @Override
    protected void onResume() {
        super.onResume();

        HashMap<String, Object> params = new HashMap<>();
        params.put("id", userId);
        params.put("role_id", roleId);
        requestManager.request(requestManager.mMessageRetrofitService.getUserHomepage(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<ContactUser>(mContext) {
                    @Override
                    public void onSuccess(ContactUser contactUser) {
                        super.onSuccess(contactUser);

                        mContactUser = contactUser;

                        GlideHelper.setCircleImage(mContext, contactUser.getUser_img(), iv, R.mipmap.icon_default_header_man);
                        tvName.setText(contactUser.getUsername());

                        SpanUtils.with(tvLikeCount)
                                .append(contactUser.getLikes_number() + "").setBold()
                                .appendLine()
                                .append("获赞").setFontSize(10, true)
                                .create();

                        SpanUtils.with(tvFansCount)
                                .append(contactUser.getFans_number() + "").setBold()
                                .appendLine()
                                .append("粉丝").setFontSize(10, true)
                                .create();

                        tvFansCount.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                FocusAndFansActivity.show(mContext, contactUser.getUsername(), contactUser.getId(), 1);
                            }
                        });

                        SpanUtils.with(tvFocusCount)
                                .append(contactUser.getFollows_number() + "").setBold()
                                .appendLine()
                                .append("关注").setFontSize(10, true)
                                .create();

                        tvFocusCount.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                FocusAndFansActivity.show(mContext, contactUser.getUsername(), contactUser.getId(), 0);
                            }
                        });

                        if (!TextUtils.isEmpty(contactUser.getBrief())) {
                            tvSign.setText(contactUser.getBrief());
                        }

                        if (contactUser.isFollowed()) {
                            ivFollowed.setVisibility(View.VISIBLE);
                            ivChat.setVisibility(View.GONE);
                            tvOperate.setText("发消息");
                        }

                        ivShare.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                HashMap<String, Object> params = new HashMap<>();
                                params.put("type", 2);
                                params.put("user_id", userId);
                                requestManager.request(requestManager.mJavaRetrofitService.share(RequestManager.getJsonRequestBody(params)),
                                        new BaseObserverImpl<ShareData>(mContext) {
                                            @Override
                                            public void onSuccess(ShareData shareData) {
                                                super.onSuccess(shareData);

                                                View view = inflater.inflate(R.layout.pop_win_message_share, null);

                                                PopupWindow popupWindow = PopupWindowHelper.getInstance(mContext).show(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                                                TextView tvName = view.findViewById(R.id.tv_name);
                                                tvName.setText(contactUser.getUsername());

                                                TextView tvOvertime = view.findViewById(R.id.tv_overtime);
                                                tvOvertime.setText("该二维码将于" + shareData.getEdt().split(" ")[0] + "到期");

                                                ImageView ivQrcode = view.findViewById(R.id.iv_qrcode);

                                                new Thread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Bitmap bitmap = QRCodeEncoder.syncEncodeQRCode(shareData.getUrl(), ScreenUtils.getScreenWidth() / 5 * 2);
                                                        ivQrcode.post(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                ivQrcode.setImageBitmap(bitmap);
                                                            }
                                                        });
                                                    }
                                                }).start();

                                                view.findViewById(R.id.tv_chat).setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        Gson gson = new Gson();
                                                        UserHomePageMessage shareUserMessage = gson.fromJson(gson.toJson(mContactUser), UserHomePageMessage.class);
                                                        shareUserMessage.setUser_id(mContactUser.getId());
                                                        Share2ContactsActivity.show(mContext, shareUserMessage);
                                                        popupWindow.dismiss();
                                                    }
                                                });
                                                view.findViewById(R.id.tv_wechat).setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        Bitmap bitmap = ImageUtils.view2Bitmap(view.findViewById(R.id.ll_share_content));

//                                                        //初始化 WXImageObject 和 WXMediaMessage 对象
//                                                        WXImageObject imgObj = new WXImageObject(bitmap);
//                                                        WXMediaMessage msg = new WXMediaMessage();
//                                                        msg.mediaObject = imgObj;
//
//                                                        //设置缩略图
//                                                        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, 160, 320, true);
//                                                        bitmap.recycle();
//
//                                                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//                                                        thumbBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//                                                        thumbBmp.recycle();
//                                                        msg.thumbData = baos.toByteArray();
//                                                        //构造一个Req
//                                                        SendMessageToWX.Req req = new SendMessageToWX.Req();
//                                                        req.transaction = "img_" + System.currentTimeMillis();
//                                                        req.message = msg;
//                                                        req.scene = SendMessageToWX.Req.WXSceneSession;
//                                                        // req.userOpenId = Constant.WX.APP_ID;
//                                                        //调用api接口，发送数据到微信
//                                                        IWXAPI api = WXAPIFactory.createWXAPI(mContext, Constant.WX.APP_ID);
//                                                        api.sendReq(req);
                                                        popupWindow.dismiss();

                                                    }
                                                });
                                                view.findViewById(R.id.tv_save).setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        PermissionHelper.getInstance().requestPermission(new PermissionHelper.RequestPermission() {
                                                            @Override
                                                            public String[] permissions() {
                                                                return new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
                                                            }

                                                            @Override
                                                            public void granted(HashSet<String> granted) {
                                                                Bitmap bitmap = ImageUtils.view2Bitmap(view.findViewById(R.id.ll_share_content));

                                                                ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG);

                                                                Toast.makeText(mContext, "已成功保存到相册", Toast.LENGTH_SHORT).show();

                                                                popupWindow.dismiss();
                                                            }

                                                            @Override
                                                            public void denied(HashSet<String> denied) {

                                                            }
                                                        });
                                                    }
                                                });
                                            }
                                        });
                            }
                        });
                    }
                });
    }

    private void focusOrNot() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("id", mContactUser.getId());
        params.put("act", mContactUser.isFollowed() ? 2 : 1);
        requestManager.request(requestManager.mMessageRetrofitService.focusOrNot(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<Object>(mContext) {
                    @Override
                    public void onSuccess() {
                        super.onSuccess();

                        mContactUser.setFollowed(!mContactUser.isFollowed());

                        if (mContactUser.isFollowed()) {
                            ivFollowed.setVisibility(View.VISIBLE);
                            ivChat.setVisibility(View.GONE);
                            tvOperate.setText("发消息");
                        } else {
                            ivFollowed.setVisibility(View.GONE);
                            ivChat.setVisibility(View.VISIBLE);
                            tvOperate.setText("关注");
                        }
                    }
                });
    }
}
































































